<?php

use Illuminate\Database\Capsule\Manager as DB;
use app\modules\Admin\models\pickgoodscardModel;

class OrderController extends CommonController
{
    public function indexAction()
    {
        $params = $this->get();
        $data = orderModel::getList($params);
        $list = $data['data'] ?? [];
        $dianpu_ids = [];
        foreach ($list as $item) {
            array_push($dianpu_ids, $item['dianpu_id']);
        }
        $dianpu = dianpuModel::whereIn('id', $dianpu_ids)->select(['id', 'name'])->get();
        foreach ($list as $k => $item) {
            foreach ($dianpu as $dianpu_item) {
                if ($dianpu_item->id == $item['dianpu_id']) {
                    $item['dianpu'] = $dianpu_item;
                }
            }
            $list[$k] = $item;
        }
        $data['data'] = $list;
        json(['code' => 1, 'msg' => '订单列表', 'data' => $data]);
    }

    public function couponsAction()
    {
        $params = $this->getPost();

        try {
            Validate::check($params, ['goods_list' => ['func'=>'isNotEmpty', 'msg'=>'商品']]);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }

        $data = orderModel::coupons($params['goods_list']);
        json(['code' => 1, 'msg' => '优惠券', 'data' => $data]);
    }

    public function preAction()
    {
        $params = $this->getPost();

        try {
            Validate::check($params, ['goods_list' => ['func'=>'isNotEmpty', 'msg'=>'商品']]);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        $user = \app\service\auth::getUser();
        $data = orderModel::previewOrder($params);
        foreach ($data['new_goods_list'] as $k=>&$v){
//            dump($data['new_goods_list']);
            if($v['category_ids'] == 276){
                if($user->is_zmd != 2){
                    throw new Exception('请先成为专卖店');
                }
            }
            if($v['goods_id'] == 983  && $user->is_zmd == 2){
                throw new Exception('您已购买过该商品');
            }
//            $is_vip = memberModel::where(['id'=>$user->id])->value('is_vip');
//            dump($user->is_vip);exit();
            if($user->is_vip == 1 && $v['detail']['current_sku_price']['vip_money']){
                $v['goods_amount'] =$v['pay_price']= $v['goods_price']  = $v['detail']['current_sku_price']['vip_money'];
                $v['detail']['current_sku_price']['price'] = $v['goods_price'];
                $v['detail']['sku_price'][0]['price'] = $v['goods_price'];
            }
        }
        if($user->is_vip == 1 && $v['detail']['current_sku_price']['vip_money']){
            $data['total_amount'] = $data['total_fee'] =$data['goods_amount'] = $data['new_goods_list'][0]['detail']['current_sku_price']['vip_money']*$data['new_goods_list'][0]['goods_num'];
        }
        $delivery_card_id = $params['delivery_card_id'] ?? 0;
        if ($delivery_card_id) {

            $member_card = DB::table('member_pickgoods_card')
                ->where('member_id', $user->id)
                ->find($delivery_card_id);
            if (!$member_card) {
                throw new Exception('用户提货卡不存在');
            }
            if ($member_card->money < $data['total_fee']) {
                throw new Exception('提货卡余额不足');
            }
            $data['delivery_card'] = $member_card;
        }

        json(['code' => 1, 'msg' => '计算成功', 'data' => $data]);
    }

    public function createorderAction()
    {
        $params = $this->getPost();

        try {
            Validate::check($params, ['goods_list' => ['func'=>'isNotEmpty', 'msg'=>'商品']]);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        $data = orderModel::createOrder($params);
        if (!$data) {
            json(['code' => 0, 'msg' => '订单提交失败']);
            exit;
        }

        json(['code' => 1, 'msg' => '订单添加成功', 'data' => $data]);
    }

    public function detailAction()
    {
        $params = $this->get();
        $detail = orderModel::detail($params);
        $items = [];
        foreach ($detail['item'] as $item) {
            $goods_combo = $item['goods_combo'];
            if (is_string($goods_combo)) {
                $item['goods_combo'] = json_decode($goods_combo, true);
            }
            $items[] = $item;
        }
        $detail['item'] = $items;
        json(['code' => 1, 'msg' => '订单详情', 'data' => $detail]);
    }

    public function zmddetailAction()
    {
        $detail =  DB::table('member_zmd_apply')->where('member_id',$this->user->id)->where('type',1)->where('agent_fee_pay_status',0)->first();
        if(!$detail){
            json(['code' => 0, 'msg' => '订单不存在']);
        }
        $detail->is_zmd = 1;
        json(['code' => 1, 'msg' => '订单详情', 'data' => $detail]);
    }

    public function itemdetailAction()
    {
        $params = $this->get();
        json(['code' => 1, 'msg' => '订单商品', 'data' => orderModel::itemDetail($params)]);
    }

    public function cancelAction()
    {
        $params = ['id' => $this->get('id')];
        try {
            Validate::check($params, ['id' => ['role' => 'required']]);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        json(['code' => 1, 'msg' => '取消成功', 'data' => orderModel::operCancel($params)]);
    }

    public function deleteAction()
    {
        $params = ['id' => $this->get('id')];
        try {
            Validate::check($params, ['id' => ['role' => 'required']]);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        json(['code' => 1, 'msg' => '删除成功', 'data' => orderModel::operDelete($params)]);
    }


    // 确认收货
    public function confirmAction()
    {
        $params = $this->getPost();
        try {
            Validate::check($params, [
                'id' => ['role' => 'required'],
                'order_item_id' => ['role' => 'required'],
            ]);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        json(['code' => 1, 'msg' => '收货成功', 'data' => orderModel::operConfirm($params)]);
    }

    // 订单商品全部确认收货
    public function confirmAllAction()
    {
        $params = $this->getPost();
        try {
            Validate::check($params, ['id' => ['role' => 'required']]);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        json(['code' => 1, 'msg' => '收货成功', 'data' => orderModel::operConfirmAll($params)]);
    }

    // 评价订单
    public function commentAction()
    {
        $params = $this->getPost();
        try {
            Validate::check($params, [
                'id' => ['role' => 'required'],
                'order_item_id' => ['role' => 'required'],
                'level' => ['role' => 'required|between:1,5', 'func' => 'isNumber'],
                'content' => ['role' => 'required'],
            ]);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        json(['code' => 1, 'msg' => '评价成功', 'data' => orderModel::operComment($params)]);
    }

    public function jsbtAction(){
        $params = ['id' => $this->get('id'),'type'=>$this->get('type')];

        try {
            Validate::check($params, ['id' => ['role' => 'required']]);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        $orderInfo = orderModel::detail($params);
        $num = count($orderInfo['item']);
        if($num != 1){
            throw new Exception('多个商品购买不能使用');
        }
        $goods = goodsskupriceModel::where(['goods_id'=>$orderInfo['item'][0]['goods_id']])->first();
        $bl    = 1;
        $consumption_scale = $orderInfo['total_amount'];
        $user              = \app\service\auth::getUser();
        if($params['type'] == 1){
            if($goods->consumption_scale > 0){
                $bl = $goods->consumption_scale;
                $consumption_scale = $orderInfo['total_amount']*$bl;
            }else{
                $consumption_scale = 0;
            }

            $user_consumption = $user->people;
        }elseif ($params['type']==4 || $params['type']==5){
            if($goods->jfdhbl > 0){
                $bl = $goods->jfdhbl;
                $consumption_scale = $orderInfo['total_amount']*$bl;
            }else{
                $consumption_scale = 0;
            }
            $user_consumption = $user->score;
        }
        if($user_consumption >= $consumption_scale){
            $money = $orderInfo['total_amount'] - $consumption_scale;
        }else{
            $money = $orderInfo['total_amount'];
        }
        json(['code' => 1, 'msg' => 'ok','data'=>round($money,2)]);
    }

}
